package com.example.module_mine.login

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import com.example.lib_common.base.BaseFragment
import com.example.lib_common.constans.IntentData
import com.example.lib_common.getAttrValue
import com.example.lib_common.observeWithLifecycle
import com.example.lib_common.state.UIState
import com.example.lib_common.utils.ToastUtils
import com.example.module_mine.R
import com.example.module_mine.databinding.FragmentSmsCodeBinding
import com.example.module_mine.login.viewmodel.LoginViewModel

/**
 * 验证码页面：登陆/忘记密码
 * 1.调用接口发送验证码，倒计时
 * 2.输入验证码
 * 3.调用接口验证验证码
 */
class SmsCodeFragment : BaseFragment<LoginViewModel,FragmentSmsCodeBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_sms_code
    override val mViewModel: LoginViewModel by activityViewModels()
    //倒计时
    private val mCountDownHandler = object :Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if(System.currentTimeMillis() - mViewModel.sendSmsCodeTimeStamp > 60 * 1000){
                hideCountDown()
            }else{
                onTick(60 - (System.currentTimeMillis() - mViewModel.sendSmsCodeTimeStamp)/1000)
            }

        }
    }

    /**
     * 执行一次
     */
    private fun onTick(sec:Long){
        //富文本
        val content = "$sec 秒后重新获得验证码"
        val builder = SpannableStringBuilder(content)
        val colorMain = getAttrValue(requireContext(), com.example.lib_common.R.attr.colorTheme)
        builder.setSpan(ForegroundColorSpan(colorMain),0,content.indexOf("秒"),Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
        mBinding.tvCountDown.text = builder
        mCountDownHandler.sendEmptyMessageDelayed(1,1000)

    }

    //action类型:登陆 / 忘记密码
    private val mAction by lazy{
        arguments?.getString(IntentData.KEY_ACTION_SMS_CODE,"").toString()
    }

    override fun initView() {
        mViewModel.setCurrentFragment(SmsCodeFragment::class.simpleName.toString())


    }

    override fun initData() {
        mBinding.viewmodel = mViewModel
        //获得验证码：根据action类型发送验证码
        if(!mAction.isNullOrEmpty()){
            mViewModel.sendSmsCode(mAction)
        }

    }

    override fun initListener() {
        //重新获取验证码
        mBinding.tvResend.setOnClickListener {
            mViewModel.sendSmsCode(mAction)
        }
        //订阅验证码
        mViewModel.mRequestSmsCode_.observeWithLifecycle(this){
            when(it){
                is UIState.Success -> {
                    setLoadingViewVisible(false)
                    ToastUtils.showLong(requireContext(),"验证码已发送")
                    mBinding.verifyView.showSoftKeyBroad() //弹出键盘
                    mViewModel.sendSmsCodeTimeStamp = System.currentTimeMillis() //记录发送验证码的时间戳
                    showCountDown() //显示倒计时
                }
                is UIState.Error -> {
                    setLoadingViewVisible(false)
                    ToastUtils.showLong(requireContext(),"获得验证码失败 $it")
                    Log.d("TAG", "initListener: $it ")
                    hideCountDown() //结束倒计时
                }
                is UIState.Loading -> {
                    setLoadingViewVisible(true,"正在获得验证码")
                }
                else -> {

                }
            }
        }
        //验证码输入完毕
        mBinding.verifyView.setOnInputVerifyCodeViewCompleted {
            if(mAction === SmsCode.LOGIN.type){
                mViewModel.loginAuth(it)
            }else if(mAction === SmsCode.RESET.type){

            }
        }
        //订阅验证码验证结果
        mViewModel.mRequestLoginAuth_.observeWithLifecycle(this){
            when(it){
                is UIState.Success -> {
                    setLoadingViewVisible(false)
                    ToastUtils.showLong(requireContext(),"登陆成功")
                    //发送全局事件总线。。。。。。
                    (requireActivity() as LoginActivity).onHandleLoginSuccess()
                }
                is UIState.Error -> {
                    setLoadingViewVisible(false)
                    ToastUtils.showLong(requireContext(),"登陆失败 $it")
                }
                is UIState.Loading -> {
                    setLoadingViewVisible(true,"正在登陆")
                }
                else -> {

                }
            }
        }

    }

    /**
     * 倒计时结束
     */
    private fun hideCountDown(){
        mBinding.tvCountDown.visibility = View.GONE
        mBinding.tvResend.visibility = View.VISIBLE
    }

    /**
     * 显示倒计时
     */
    private fun showCountDown(){
        mBinding.tvCountDown.visibility = View.VISIBLE
        mBinding.tvResend.visibility = View.GONE
        mCountDownHandler.sendEmptyMessage(1)
    }

    override fun onDestroy() {
        super.onDestroy()
        mCountDownHandler.removeCallbacksAndMessages(null) //移除未处理的消息防止handler内存泄漏
    }

}
enum class SmsCode(val type:String){
    LOGIN("login"),RESET("reset")
}